<template>
	<div class="content">
		<cl-crud @load="onLoad">
			<template #slot-content>
				<div class="slot-content">
					<div class="amount-list">
						<div class="amount-item">
							<p>可提现金币：</p>
							<span>{{ subData.availableGoldAmount }}</span>
						</div>
						<div class="amount-item">
							<p>待结算金币：</p>
							<span>{{ subData.unpaidGoldAmount }}</span>
						</div>
						<div class="amount-item">
							<p>已提现金币：</p>
							<span>{{ subData.paidGoldAmount }}</span>
						</div>
						<div class="amount-item">
							<p>提现申请中金币：</p>
							<span>{{ subData.audittingGoldAmount }}</span>
						</div>
					</div>
					<p class="careful">注意：10金币=1元RMB</p>
					<p class="bind" v-if="alipay.length === 0">
						您尚未绑定支付宝账号，<span @click="zfbVisible = true">点击立即绑定</span>
					</p>
					<p class="bind" v-else>
						提现到支付宝：{{ alipay[0].account
						}}<span @click="zfbVisible = true" style="margin-left: 10px"
							>点击修改支付宝</span
						>
					</p>

					<div class="withdraw">
						<p class="label">提现金币数：</p>
						<el-input-number
							v-model="goldAmount"
							size="small"
							:precision="1"
							:step="0.5"
							:min="0"
							:max="parseFloat(subData.availableGoldAmount)"
							placeholder="请输入要提现的金币数"
						></el-input-number>
						<el-button type="success" size="small" @click="withdrawAll"
							>全部金币</el-button
						>
						<p class="desc">
							您要提现的金币数为{{ goldAmount }}金币，可获得<span>{{
								parseFloat(goldAmount) / 10
							}}</span
							>元
						</p>
					</div>
					<el-button type="primary" style="width: 224px" size="small" @click="onWithdraw"
						>立即提现</el-button
					>
				</div>
			</template>
			<template #table-column-amount="{ scope }">
				<span class="amount">{{ scope.row.amount }}元</span>
				<span class="goldAmount">({{ scope.row.goldAmount }}金币)</span>
			</template>

			<template #table-column-status="{ scope }">
				<el-tag type="primary" v-if="scope.row.status === 0">审核中</el-tag>
				<el-tag type="success" v-if="scope.row.status === 1">审核通过，待打款</el-tag>
				<el-tag type="info" v-if="scope.row.status === 2">已驳回</el-tag>
				<el-tag type="success" v-if="scope.row.status === 3">提现成功</el-tag>
				<el-tag type="danger" v-if="scope.row.status === 4">打款失败</el-tag>
			</template>
		</cl-crud>
		<el-dialog title="编辑我的支付宝" :visible.sync="zfbVisible" width="550px">
			<div class="zfb-dialog" v-loading="loading">
				<el-form size="medium">
					<el-form-item label="手机号码">
						<el-input
							v-model="form.phone"
							placeholder="请输入手机号"
							maxlength="11"
							clearable
							style="width: 380px"
						></el-input>
					</el-form-item>

					<el-form-item class="captcha" label="校验码">
						<el-input
							placeholder="请输入获取到的短信验证码"
							v-model="form.code"
							maxlength="4"
							style="width: 250px;margin-right: 20px"
							clearable
						></el-input>

						<el-button @click="getCaptcha" :disabled="captcha.btnLock">{{
							typeof captcha.state === 'number' ? captcha.state + 's' : captcha.state
						}}</el-button>
					</el-form-item>

					<el-form-item label="支付宝">
						<el-input
							v-model="form.account"
							style="width: 380px"
							placeholder="请输入支付宝"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item label="支付宝实名人">
						<el-input
							v-model="form.name"
							style="width: 380px"
							placeholder="请输入支付宝实名人"
							clearable
						></el-input>
					</el-form-item>
				</el-form>
			</div>
			<div class="dialog-footer">
				<el-button @click="zfbVisible = false">取 消</el-button>
				<el-button type="primary" @click="bindZfb">确 定</el-button>
			</div>
		</el-dialog>

		<captcha ref="captcha" @callback="captchaCountDown"></captcha>
	</div>
</template>

<script>
import Captcha from '@/components/captcha';
export default {
	name: 'cash',
	components: {
		Captcha
	},
	data() {
		return {
			subData: {},
			alipay: [],
			goldAmount: 0,
			btnLock: false,
			zfbVisible: false,
			form: {},
			loading: false,
			captcha: {
				interval: null,
				btnLock: false,
				state: '获取验证码'
			}
		};
	},
	created() {
		// 获取支付宝绑定状态
		this.getAlipayAccount();
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.promotion.withdrawLog)
				.set('table', {
					columns: [
						{
							type: 'index',
							label: '序号',
							align: 'center',
							width: '60px'
						},
						{
							label: '流水号',
							prop: 'tradeNo',
							align: 'center'
						},
						{
							label: '提现日期',
							prop: 'createTime',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '提现金额',
							prop: 'amount',
							align: 'center'
						},
						{
							label: '提现账户',
							prop: 'account',
							align: 'center'
						},
						{
							label: '提现状态',
							prop: 'status',
							align: 'center'
						},
						{
							label: '备注',
							prop: 'reason',
							align: 'center'
						}
					],
					op: {
						visible: false // 是否显示
					},
					props: {
						'default-sort': {
							prop: 'createTime',
							order: 'descending'
						}
					}
				})
				.set('layout', [
					['refresh-btn'],
					['slot-content'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next, render }) => {
					const { list, subData } = await next(params);
					// list.forEach(item => {
					// 	item.couponStarttime = moment(parseInt(item.couponStarttime)).format('YYYY-MM-DD HH:mm:ss');
					// 	item.couponEndtime = moment(parseInt(item.couponEndtime)).format('YYYY-MM-DD HH:mm:ss');
					// })
					this.subData = subData;
					render(list);
				})
				.done();
			app.refresh();
		},
		refresh(params) {
			this.crud.refresh(params);
		},
		getAlipayAccount() {
			this.$service.promotion.alipay.page().then(res => {
				this.alipay = res.list;

				if (res.list.length > 0) {
					this.form.phone = res.list[0].phone;
					this.form.account = res.list[0].account;
					this.form.name = res.list[0].name;
				}
			});
		},
		withdrawAll() {
			this.goldAmount = parseFloat(this.subData.availableGoldAmount);
		},
		onWithdraw() {
			if (this.alipay.length === 0) {
				this.$message.error('请选绑定支付宝账号');
				return false;
			} else {
				if (parseFloat(this.goldAmount) >= 10) {
					if (!this.btnLock) {
						this.btnLock = true;
						this.$service.promotion.withdrawLog
							.add({
								alipayId: this.alipay[0].id,
								goldAmount: this.goldAmount
							})
							.then(() => {
								this.$message.success('发起提现成功');
								this.refresh();
								this.btnLock = false;
							})
							.catch(err => {
								this.$message.error(err);
								this.btnLock = false;
							});
					}
				} else {
					this.$message.error('提现金额最小不低于1元');
					return false;
				}
			}
		},
		// 获取短信验证码
		getCaptcha() {
			if (/^(?:(?:\+|00)86)?1\d{10}$/.test(this.form.phone)) {
				this.$refs['captcha'].open(this.form.phone);
			} else {
				this.$message.warning('请输入正确的手机号');
			}
		},
		captchaCountDown() {
			// 验证码倒计时
			this.captcha.state = 60;
			this.captcha.btnLock = true;

			this.captcha.interval = setInterval(() => {
				this.captcha.state--;
				if (this.captcha.state === 0) {
					clearInterval(this.captcha.interval);
					this.captcha.state = '重新发送';
					this.captcha.btnLock = false;
				}
			}, 1000);
		},
		bindZfb() {
			const { phone, code, account, name } = this.form;
			const { captchaId } = this.$refs['captcha'].form;

			if (!phone) {
				return this.$message.warning('手机号不能为空');
			}

			if (!captchaId) {
				return this.$message.warning('请选获取短信验证码');
			}

			if (!code) {
				return this.$message.warning('短信验证码不能为空');
			}

			if (!account) {
				return this.$message.warning('支付宝账号不能为空');
			}

			if (!name) {
				return this.$message.warning('支付宝实名人不能为空');
			}

			this.loading = true;

			// 新增支付宝
			if (this.alipay.length === 0) {
				this.$service.promotion.alipay
					.add({
						phone,
						code,
						account,
						name,
						captchaId
					})
					.then(() => {
						this.$message.success('绑定成功');
						this.zfbVisible = false;
						this.refresh();
						this.form = {};
						this.getAlipayAccount();
					})
					.catch(err => {
						this.$message.error(err);
					})
					.done(() => {
						this.loading = false;
					});
			} else {
				this.$service.promotion.alipay
					.update({
						phone,
						code,
						account,
						name,
						captchaId,
						id: this.alipay[0].id
					})
					.then(() => {
						this.$message.success('修改成功');
						this.zfbVisible = false;
						this.refresh();
						this.form = {};
						this.getAlipayAccount();
					})
					.catch(err => {
						this.$message.error(err);
					})
					.done(() => {
						this.loading = false;
					});
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
.slot-content {
    .amount-list {
        margin-bottom 20px
        flexBox(flex-start, center)
        .amount-item {
            text-align center
            padding 20px 30px
            color #333
            border-right 1px solid #ccc
            &:last-child {
                border-right none
            }
            p {
                margin-bottom 10px
            }
            span {
                color $main-color
            }
        }
    }
}
    .amount {
        color $main-color
    }
        .careful {
            color $main-color
            font-size 24px
            margin-bottom 20px
        }
    .bind {
        font-size 14px
        span {
            color $main-color
            cursor pointer
        }
    }
    .withdraw {
        margin-top 20px
        margin-bottom 10px
        font-size 14px
        flexBox(flex-start, center);
        .label {
            margin-right 10px
        }
        /deep/.el-button {
            margin-left 20px
        }
        .desc {
            margin-left 20px
            span {
                color $main-color
            }
        }
    }
    .zfb-dialog {
        /deep/.el-form {
            .el-form-item {
                flexBox(flex-start)
                .el-form-item__label {
                    width 100px
                }
                .el-form-item__content {
                    flexBox(flex-start)
                }
            }
        }
    }
</style>
